//
//  UIView+ZXHelper.m
//  ShiChunTang
//
//  Created by simon on 13/11/1.
//  Copyright (c) 2013年 yinyuetai.com. All rights reserved.
//

#import "UIView+ZXBorder.h"

@implementation UIView (ZXBorder)

- (void)zx_setBorderWithCornerRadius:(CGFloat)cornerRadius
{
    self.layer.masksToBounds = YES;
    self.layer.cornerRadius = cornerRadius;
}

- (void)zx_setBorderWithCornerRadius:(CGFloat)cornerRadius
                         borderWidth:(CGFloat)borderWidth
                         borderColor:(nullable UIColor *)borderColor
{
    self.layer.masksToBounds = YES;
    self.layer.cornerRadius = cornerRadius;
    self.layer.borderWidth = borderWidth;
    self.layer.borderColor = borderColor?[borderColor CGColor]:[UIColor clearColor].CGColor;
}


- (void)zx_setBorderWithCornerRadius:(CGFloat)cornerRadius
                       maskedCorners:(CACornerMask)maskedCorners
                         borderWidth:(CGFloat)borderWidth
                         borderColor:(nullable UIColor *)borderColor
{
    [self zx_setBorderWithCornerRadius:cornerRadius borderWidth:borderWidth borderColor:borderColor];
    if (@available(iOS 11.0, *)) {
        self.layer.maskedCorners = maskedCorners;
    } else {
        // Fallback on earlier versions
    }
}




- (void)zx_setBorderMaskWithCircleShapeWithBounds:(CGRect)rect
{
    CGFloat x = rect.size.width/2.0;
    CGFloat y = rect.size.height/2.0;
    CGFloat cornerRadius = MIN(x, y);
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(x, y) radius:cornerRadius startAngle:0 endAngle:2*M_PI clockwise:YES];
    if (![self.layer.mask isKindOfClass:[CAShapeLayer class]]) {
        CAShapeLayer *shapeLayer = [[CAShapeLayer alloc] init];
        self.layer.mask = shapeLayer;
        shapeLayer.path = bezierPath.CGPath;
    }else{
        CAShapeLayer *shapeLayer = (CAShapeLayer *)self.layer.mask;
        shapeLayer.path = bezierPath.CGPath;
    }
}


- (void)zx_setBorderWithCornerRadius:(CGFloat)cornerRadius
                           boundsSize:(CGSize)size
                     roundingCorners:(UIRectCorner)cornersType
                         borderWidth:(CGFloat)borderWidth
                         borderColor:(nullable UIColor *)borderColor
{
    CGSize cornerRadii = CGSizeMake(cornerRadius, borderWidth);
    ///设置显示图形区域
    UIBezierPath *maskShapePath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, size.width, size.height) byRoundingCorners:cornersType cornerRadii:cornerRadii];
    if (![self.layer.mask isKindOfClass:[CAShapeLayer class]]) {
        CAShapeLayer *maskShapeLayer = [[CAShapeLayer alloc] init];
        self.layer.mask = maskShapeLayer;
        maskShapeLayer.path = maskShapePath.CGPath;
    }else{
        CAShapeLayer *maskShapeLayer = (CAShapeLayer *)self.layer.mask;
        maskShapeLayer.path = maskShapePath.CGPath;
    }
    
    NSUInteger index = [self.layer.sublayers indexOfObjectPassingTest:^BOOL(__kindof CALayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        return [obj.name isEqualToString:@"borderBounds"];
    }];
    ///插入边框图层
    if (borderWidth >0) {
        CGRect borderBounds = CGRectMake(borderWidth/2.0, borderWidth/2.0, size.width-borderWidth, size.height-borderWidth);
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:borderBounds byRoundingCorners:cornersType cornerRadii:cornerRadii];
        
        if (index == NSNotFound || !self.layer.sublayers){
            CAShapeLayer *shapeLayer  = [CAShapeLayer layer];
            shapeLayer.strokeColor = borderColor.CGColor;
            ///不填充
            shapeLayer.fillColor = nil;
            shapeLayer.lineWidth = borderWidth;
            shapeLayer.lineJoin = kCALineJoinRound;
            shapeLayer.lineCap = kCALineCapButt;
            shapeLayer.path = path.CGPath;
            shapeLayer.name = @"borderBounds";
            [self.layer addSublayer:shapeLayer];
        }
        else{
            CALayer *layer = [self.layer.sublayers objectAtIndex:index];
            CAShapeLayer *shapeLayer = (CAShapeLayer *)layer;
            shapeLayer.strokeColor = borderColor.CGColor;
            shapeLayer.lineWidth = borderWidth;
            shapeLayer.path = path.CGPath;
        }
     }
    ///移除边框图层
    else if(index != NSNotFound && borderWidth == 0){
        CALayer *layer = [self.layer.sublayers objectAtIndex:index];
        [layer removeFromSuperlayer];
    }
}




- (void)zx_setBorderWithWithCornerRadius:(CGFloat)cornerRadius
                              boundsSize:(CGSize)size
                        roundingCorners:(UIRectCorner)cornersType
                               topBorder:(BOOL)top
                              leftBorder:(BOOL)left
                            bottomBorder:(BOOL)bottom
                             rightBorder:(BOOL)right
                             borderWidth:(CGFloat)borderWidth
                             borderColor:(UIColor *)borderColor
{
    ///设置显示图形区域
    if (cornerRadius >0) {
        CGSize cornerRadii = CGSizeMake(cornerRadius, borderWidth);
        UIBezierPath *maskShapePath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, size.width, size.height) byRoundingCorners:cornersType cornerRadii:cornerRadii];
        if (![self.layer.mask isKindOfClass:[CAShapeLayer class]]) {
            CAShapeLayer *maskShapeLayer = [[CAShapeLayer alloc] init];
            self.layer.mask = maskShapeLayer;
            maskShapeLayer.path = maskShapePath.CGPath;
        }else{
            CAShapeLayer *maskShapeLayer = (CAShapeLayer *)self.layer.mask;
            maskShapeLayer.path = maskShapePath.CGPath;
        }
    }else{
        self.layer.mask = nil;
    }
    ///按顺时针绘制线段+曲线段
    NSUInteger index = [self.layer.sublayers indexOfObjectPassingTest:^BOOL(__kindof CALayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        return [obj.name isEqualToString:@"borderBounds"];
    }];
    ///插入边框图层
    if (borderWidth >0) {
        
        CGFloat strokeOffest = borderWidth/2;
        UIBezierPath *path = [UIBezierPath bezierPath];
        if (top) {
            if (cornersType & UIRectCornerTopLeft) {
                [path moveToPoint:CGPointMake(cornerRadius+strokeOffest, 0+strokeOffest)];
            }else{
                [path moveToPoint:CGPointMake(0+strokeOffest, 0+strokeOffest)];
            }
            if (cornersType & UIRectCornerTopRight) {
                [path addLineToPoint:CGPointMake(size.width-cornerRadius-strokeOffest, 0+strokeOffest)];
            }else{
                [path addLineToPoint:CGPointMake(size.width-2*strokeOffest, 0+strokeOffest)];
            }
        }
        ///如果有圆角
        if (cornersType & UIRectCornerTopRight) {
            ///把点移动过来
            if (!top) {
                [path moveToPoint:CGPointMake(size.width-cornerRadius-2*strokeOffest, 0+strokeOffest)];
            }
            [path addArcWithCenter:CGPointMake(size.width-cornerRadius-2*strokeOffest, cornerRadius+strokeOffest) radius:cornerRadius startAngle:M_PI*(270)/180.0 endAngle:M_PI*(360)/180.0 clockwise:YES];
        }
        
        if (right) {
            ///如果之前没圆角，把点移动过来
            if (cornersType & UIRectCornerTopRight) {
            }else{
                [path moveToPoint:CGPointMake(size.width-2*strokeOffest, 0)];
            }
            ///如果下个有圆角
            if (cornersType & UIRectCornerBottomRight) {
                [path addLineToPoint:CGPointMake(size.width-2*strokeOffest, size.height-cornerRadius-2*strokeOffest)];
            }else{
                [path addLineToPoint:CGPointMake(size.width-2*strokeOffest, size.height-2*strokeOffest)];
            }
        }
        if (cornersType & UIRectCornerBottomRight) {
            if (!right) {
                [path moveToPoint:CGPointMake(size.width-2*strokeOffest, size.height-cornerRadius-2*strokeOffest)];
            }
            [path addArcWithCenter:CGPointMake(size.width-cornerRadius-2*strokeOffest, size.height-cornerRadius-2*strokeOffest) radius:cornerRadius startAngle:0 endAngle:M_PI*(90)/180.0 clockwise:YES];
        }
        if (bottom) {
            if (cornersType & UIRectCornerBottomRight) {
            }else{
                [path moveToPoint:CGPointMake(size.width-2*strokeOffest, size.height-2*strokeOffest)];
            }
            if (cornersType & UIRectCornerBottomLeft) {
                [path addLineToPoint:CGPointMake(cornerRadius+strokeOffest, size.height-2*strokeOffest)];
            }else{
                [path addLineToPoint:CGPointMake(0+strokeOffest, size.height-2*strokeOffest)];
            }
        }
        if (cornersType & UIRectCornerBottomLeft) {
            if (!bottom) {
                [path moveToPoint:CGPointMake(cornerRadius+strokeOffest, size.height-2*strokeOffest)];
            }
            [path addArcWithCenter:CGPointMake(cornerRadius+strokeOffest, size.height-cornerRadius-2*strokeOffest) radius:cornerRadius startAngle:M_PI*(90)/180.0 endAngle:M_PI*(180)/180.0 clockwise:YES];
        }
        if (left) {
            if (cornersType & UIRectCornerBottomLeft) {
            }else{
                [path moveToPoint:CGPointMake(0+strokeOffest, size.height-2*strokeOffest)];
            }
            if (cornersType & UIRectCornerTopLeft) {
                [path addLineToPoint:CGPointMake(0+strokeOffest, cornerRadius+strokeOffest)];
            }else{
                [path addLineToPoint:CGPointMake(0+strokeOffest, 0+strokeOffest)];
            }
        }
        if (cornersType & UIRectCornerTopLeft) {
            if (!left) {
                [path moveToPoint:CGPointMake(0+strokeOffest, cornerRadius+strokeOffest)];
            }
            [path addArcWithCenter:CGPointMake(cornerRadius+strokeOffest, cornerRadius+strokeOffest) radius:cornerRadius startAngle:M_PI*(180)/180.0 endAngle:M_PI*(270)/180.0 clockwise:YES];
        }
        
        if (index == NSNotFound || !self.layer.sublayers){
            CAShapeLayer *shapeLayer  = [CAShapeLayer layer];
            shapeLayer.strokeColor = borderColor.CGColor;
            ///不填充
            shapeLayer.fillColor = nil;
            shapeLayer.lineWidth = borderWidth;
            shapeLayer.lineJoin = kCALineJoinRound;
            shapeLayer.lineCap = kCALineCapButt;
            shapeLayer.path = path.CGPath;
            shapeLayer.name = @"borderBounds";
            [self.layer addSublayer:shapeLayer];
        }
        else{
            CALayer *layer = [self.layer.sublayers objectAtIndex:index];
            CAShapeLayer *shapeLayer = (CAShapeLayer *)layer;
            shapeLayer.strokeColor = borderColor.CGColor;
            shapeLayer.lineWidth = borderWidth;
            shapeLayer.path = path.CGPath;
        }
    }
    ///移除边框图层
    else if(index != NSNotFound && borderWidth == 0){
        CALayer *layer = [self.layer.sublayers objectAtIndex:index];
        [layer removeFromSuperlayer];
    }
    
    /*
    ///如果是nil数组，会默认值0
    NSUInteger topIndex = [self.layer.sublayers indexOfObjectPassingTest:^BOOL(__kindof CALayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        return [obj.name isEqualToString:@"top"];
    }];
    if (top) {
        if (topIndex == NSNotFound || !self.layer.sublayers){
            CALayer *layer = [CALayer layer];
            layer.frame = CGRectMake(0, 0, size.width, borderWidth);
            layer.backgroundColor = borderColor.CGColor;
            layer.name = @"top";
            [self.layer addSublayer:layer];
        }else{
            CALayer *layer = [self.layer.sublayers objectAtIndex:topIndex];
            layer.frame = CGRectMake(0, 0, size.width, borderWidth);
            layer.backgroundColor = borderColor.CGColor;
        }
    }else{
        if (topIndex != NSNotFound && self.layer.sublayers){
            CALayer *layer = [self.layer.sublayers objectAtIndex:topIndex];
            [layer removeFromSuperlayer];
        }
    }

    NSUInteger rightIndex = [self.layer.sublayers indexOfObjectPassingTest:^BOOL(__kindof CALayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        return [obj.name isEqualToString:@"right"];
    }];
    if (right) {
        if (rightIndex == NSNotFound || !self.layer.sublayers){
            CALayer *layer = [CALayer layer];
            layer.frame = CGRectMake(size.width - borderWidth, 0, borderWidth, size.height);
            layer.backgroundColor = borderColor.CGColor;
            layer.name = @"right";
            [self.layer addSublayer:layer];
        }else{
            CALayer *layer = [self.layer.sublayers objectAtIndex:rightIndex];
            layer.frame = CGRectMake(size.width - borderWidth, 0, borderWidth, size.height);
            layer.backgroundColor = borderColor.CGColor;
        }
    }else{
        if (rightIndex != NSNotFound || self.layer.sublayers){
            CALayer *layer = [self.layer.sublayers objectAtIndex:rightIndex];
            [layer removeFromSuperlayer];
        }
    }
    
    NSUInteger bottomIndex = [self.layer.sublayers indexOfObjectPassingTest:^BOOL(__kindof CALayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        return [obj.name isEqualToString:@"bottom"];
    }];
    if (bottom) {
        if (bottomIndex == NSNotFound || !self.layer.sublayers){
            CALayer *layer = [CALayer layer];
            layer.frame = CGRectMake(0, size.height - borderWidth, size.width, borderWidth);
            layer.backgroundColor = borderColor.CGColor;
            layer.name = @"bottom";
            [self.layer addSublayer:layer];
        }else{
            CALayer *layer = [self.layer.sublayers objectAtIndex:bottomIndex];
            layer.frame = CGRectMake(0, size.height - borderWidth, size.width, borderWidth);
            layer.backgroundColor = borderColor.CGColor;
        }
    }else{
        if (bottomIndex != NSNotFound && self.layer.sublayers){
            CALayer *layer = [self.layer.sublayers objectAtIndex:bottomIndex];
            [layer removeFromSuperlayer];
        }
    }
    
    NSUInteger leftIndex = [self.layer.sublayers indexOfObjectPassingTest:^BOOL(__kindof CALayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        return [obj.name isEqualToString:@"left"];
    }];
    if (left) {
        if (leftIndex == NSNotFound || !self.layer.sublayers){
            CALayer *layer = [CALayer layer];
            layer.frame = CGRectMake(0, 0, borderWidth, size.height);
            layer.backgroundColor = borderColor.CGColor;
            layer.name = @"left";
            [self.layer addSublayer:layer];
        }
        else{
            CALayer *layer = [self.layer.sublayers objectAtIndex:leftIndex];
            layer.frame = CGRectMake(0, 0, borderWidth, size.height);
            layer.backgroundColor = borderColor.CGColor;
        }
    }else{
        if (leftIndex != NSNotFound || self.layer.sublayers){
            CALayer *layer = [self.layer.sublayers objectAtIndex:leftIndex];
            [layer removeFromSuperlayer];
        }
    }
     */
}





- (void)zx_setShadowColor:(nullable UIColor *)shadowColor shadowOpacity:(CGFloat)opacity shadowOffset:(CGSize)offset shadowRadius:(CGFloat)shadowRadius
{
    // cannot have masking
    self.layer.masksToBounds = NO;
    
    self.layer.shadowColor=shadowColor?shadowColor.CGColor:[UIColor blackColor].CGColor;
    self.layer.shadowOpacity=opacity;
    self.layer.shadowOffset=offset;
    self.layer.shadowRadius = shadowRadius;
}




- (void)zx_updateShadowPathToBounds:(CGRect)bounds withDuration:(NSTimeInterval)duration
{
    CGPathRef oldPath = self.layer.shadowPath;
    CGPathRef newPath = CGPathCreateWithRect(bounds, NULL);
    
    if (oldPath && duration>0)
    {
        CABasicAnimation *theAnimation = [CABasicAnimation animationWithKeyPath:@"shadowPath"];
        theAnimation.duration = duration;
        theAnimation.fromValue = (__bridge id)oldPath;
        theAnimation.toValue = (__bridge id)newPath;
        theAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        [self.layer addAnimation:theAnimation forKey:@"shadowPath"];
    }
    
    self.layer.shadowPath = newPath;
    
    CGPathRelease(newPath);
}

@end
